//
// Created by denglibin on 2021/3/29.
//

// 一定要注意顺序！！
#include <glad/glad.h>
#include <SDL.h>

#define WIN_WIDTH 960
#define WIN_HEIGHT 600
#define FRAME_RATE 60 //帧率
#define FONT_SIZE 32
static struct SDL_Window * win; //窗口
static SDL_GLContext glContext;
// 模拟顶点数据
//三角形
GLfloat triangleVertices[] = {
        -0.5f, -0.5f, 0.0f,  //左下
        0.5f, -0.5f, 0.0f,  //右下
        0.0f,  0.5f, 0.0f,   //中上
};
static void draw(){
    GLuint VBO,VAO;
    //创建VBO
    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(triangleVertices), triangleVertices, GL_STATIC_DRAW);


    //创建VAO
    glGenVertexArrays(1, &VAO);
    //glBindVertexArray(VAO);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    //解绑VAO
    //glBindVertexArray(0);

    //线框模式
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    //渲染指令
    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    glDrawArrays(GL_TRIANGLES, 0, 3);
    //解绑VAO
    glBindVertexArray(0);
    //交换缓冲
    SDL_GL_SwapWindow(win);
}
/**
 * 事件循环
 */
static void eventLoop(){
    SDL_Event  event;
    while (1)
    {//主消息循环
        SDL_PollEvent(&event);
        if(event.type == SDL_QUIT){
            return;
        }
        draw();

        uint32_t  begin = SDL_GetTicks();
        uint32_t  end = SDL_GetTicks();
        uint32_t  cost = end - begin;
        uint32_t per_frame_time = 1000 / FRAME_RATE;//每一帧耗时ms
        if (per_frame_time > cost){
            //减去循环体耗时，得到还应休眠的时间
            SDL_Delay(per_frame_time - cost);
        }
    }

}

/**
 * 初始化操作
 */
static void init(){
    //初始化，成功返回0
    if (SDL_Init(SDL_INIT_VIDEO)) {
        SDL_Log("Can not init video %s\n", SDL_GetError());
        exit(1);
    }
    gladLoadGL();
}
/**
 * 创建显示窗口
 * @return
 */
static int showWindow(){

    win = SDL_CreateWindow("Hello GL",
                           SDL_WINDOWPOS_CENTERED,
                           SDL_WINDOWPOS_CENTERED,
                           WIN_WIDTH,
                           WIN_HEIGHT,
                           SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN
    );
    if (win == NULL) {
        SDL_Log("Can not create window %s\n", SDL_GetError());
        return 2;
    }

    glContext =  SDL_GL_CreateContext(win);
    //把OpenGL的函数指针导入给GLAD
    gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress);
    return 0;

}
/**
 * 清理
 */
static void clean(){
    SDL_GL_DeleteContext(glContext);
    SDL_DestroyWindow(win);
    SDL_Quit();
}
int main3_1(int argc, char* argv[]){
    init();
    if (showWindow()){
        exit(1);
    }
    eventLoop();
    clean();
}